package com.example.common.network;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitServiceManager {
    private static final int DEFAULT_CONNECT_TIME = 10;
    private static final int DEFAULT_WRITE_TIME = 30;
    private static final int DEFAULT_READ_TIME = 30;
    private final OkHttpClient okHttpClient;
    private final static String BASE_URL="https://www.tlianfou.top/api/";
    private final Retrofit retrofit;

    private RetrofitServiceManager(){

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)//连接超时时间
                .writeTimeout(DEFAULT_WRITE_TIME, TimeUnit.SECONDS)//设置写操作超时时间
                .readTimeout(DEFAULT_READ_TIME, TimeUnit.SECONDS)//设置读操作超时时间
                .build();

        //创建retrofit实例
        retrofit=new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)//设置baseUrl
                .addConverterFactory(GsonConverterFactory.create())//设置使用Gson解析
                .build();
    }

    /**
     * 唯一实例持有类
     */
    private static class SingleHolder{
            private static final RetrofitServiceManager INSTANCE=new RetrofitServiceManager();
    }

    public static RetrofitServiceManager getInstance(){
        return SingleHolder.INSTANCE;
    }

    /**
     * 创建网络接口实例
     * @param service
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service){return retrofit.create(service);}
}
